<?php


namespace app\api\validate;


use app\common\enum\FlagEnum;
use app\common\exception\ParameterException;

class OrderPlace extends BaseValidate
{
    // 如果是单规格商品, flag=1则product_id==sku_id
    // 如果是多规格商品, flag=2则product_id,sku_id
    protected $products = [
        [
            'flag' => FlagEnum::Single,
            'product_id' => 1,
            'sku_id' => 1,
            'count' => 30
        ],
        [
            'flag' => FlagEnum::Multiple,
            'product_id'=> 15,
            'sku_id' => 5,
            'count' => 20
        ]
    ];

    protected $rule = [
        'products' => 'checkProducts'
    ];

    protected $itemRule = [
        'flag' => 'require|integer|in:-1,1',
        'product_id' => 'require|isPositiveInt',
        'sku_id' => 'require|isPositiveInt',
        'count' => 'require|isPositiveInt'
    ];

    protected function checkProducts($values)
    {
        $a  = 1;
        if(!is_array($values))
        {
            throw new ParameterException(['msg' => '商品参数不对']);
        }
        if(empty($values))
        {
            throw new ParameterException(['msg' => '商品列表不能为空']);
        }

        foreach($values as $value){
            $this->checkMyItem($value);
        }
        return true;
    }

    protected function checkMyItem($value)
    {
        $validate = new BaseValidate($this->itemRule);
        $res = $validate->check($value);
        if(!$res)
        {
            throw new ParameterException(['msg' => '商品列表参数错误']);
        }
    }
}